<?php
// +----------------------------------------------------------------------
// | 在我们年轻的城市里，没有不可能的事！
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.mysite.com All rights reserved.
// +----------------------------------------------------------------------
// | Author : Jansen <jansen.shi@qq.com>
// +----------------------------------------------------------------------
namespace jansen\utils\ip;
class IP{
    private $handler;
    /**
     * IP constructor.
     *
     * @param string $driver 驱动名称
     * @param array  $config 特定驱动的配置
     */
    public function __construct(string $driver, array $config=[]){
        $this->setDriver($driver, $config);
    }
    /**
     * 切换IP获取引擎
     * @param string $driver 驱动名称
     * @param array  $config 特定驱动的配置
     * @author:Jansen <jansen.shi@qq.com>
     */
    public function setDriver(string $driver, array $config=[]){
        $class = 'jansen\\utils\\ip\\drivers\\'.ucfirst(strtolower($driver));
        $this->handler = new $class($config);
    }
    /**
     * 动态调用方法
     * @param string $method
     * @param array $args
     * @return mixed
     * @throws \Exception
     * @author:Jansen <jansen.shi@qq.com>
     */
    public function __call(string $method, array $args){
        if(method_exists($this->handler, $method)){
            return call_user_func_array([$this->handler, $method], $args);
        }else{
            throw new \Exception('调用了未知方法，请检查。', E_USER_ERROR);
        }
    }
    /**
     * 取IP对应的地址
     * @param string $ip   ip地址
     * @return array
     * @author:Jansen <jansen.shi@qq.com>
     */
    public function address(string $ip){
        try{
            $result = call_user_func_array([$this->handler, 'ip2addr'], ['ip' => $ip]);
            return ['status'=>200, 'message'=>$result];
        }catch(TranslateException $e){
            return ['status'=>500, 'message'=>$e->getErrorMessage()];
        }
    }
}